<template>

<div class="banner">
    <div class="bannerTop">
        <a-input-search class="search" v-model:value="keyWords" :placeholder="$t('search.placeholder')"
            enter-button="搜索" @search="onSearch" allowClear />
        <a-button @click="toAdd">

            <template #icon>
                <PlusOutlined style="font-weight: lighter;" />
            </template>
            添加
        </a-button>
    </div>

    
    <a-table class="table" 
    :columns="columns"
    :rowKey="(record)=>record.id"
    :data-source="data" 
    :row-selection="rowSelection" 
    :pagination="false"
    :loading="isLoading"
    :scroll="{y:`calc(100vh - 288px)`}"
    >
        <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">

               <a-button-group>
                <button size="small"  ghost type="primary" @click="toEdit(record)">编辑</button>
                <button size="small"  ghost danger @click="remove(true,record)">删除</button>
               </a-button-group>
            </template>
             <template v-if="column.dataIndex === 'pic'">

                  <a-image
                    :width="60"
                    :height="60"
                     :src="record.pic"
                    />
            </template>

            <template v-if="column.dataIndex === 'status'">
                <a-tag color="#87d068" v-if="record.status">
                    {{ $t("btn.start") }}
                </a-tag>
                <a-tag color="#f50" v-else>关闭</a-tag>

            </template>
        </template>




    </a-table>

    <div class="pages">

        <a-button danger :disabled="selectedKeys.length === 0" @click="remove(false)">删除选中</a-button>

        <a-pagination 
        v-model:current="page" 
        :total="500"
        :page-size-options="pageSizeOptions"
        show-size-changer
        @showSizeChange="onShowSizeChange"
        v-model:pageSize="limit"
        >
        <!-- <template #buildOptionText="props">
      <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
    </template> -->
             <template #itemRender="{ type, originalElement }">
                 <a v-if="type === 'prev'">上一页</a>
                 <a v-else-if="type === 'next'">下一页</a>
                <component :is="originalElement" v-else></component>
             </template>
        </a-pagination>
    </div>


</div>
</template>
<style scoped lang="less">

.banner {
    padding: 0 20px;
    .bannerTop {
        display: flex;
        justify-content: space-between;
        .search {
            max-width: 300px;
        }
    }

}

.table {
    margin: 20px 0;
}

.pages {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    background: #ffffff;

}
</style>
<script setup>
// import { log } from 'echarts/types/src/util/log.js';
import { ref,createVNode } from 'vue';
import { PlusOutlined,ExclamationCircleOutlined} from '@ant-design/icons-vue';
import { Modal,message as Msg } from 'ant-design-vue';

import { useRouter } from 'vue-router';
import columns from './table.config'
// import data from './data.config'
import { getBannerListApi,delBannerListApi} from '../../../api/banner';
import {handlerPicPath} from "../../../utils/tools"
// import { watch } from 'less';
const keyWords = ref('');
const data = ref([]);
// 当前页
const page = ref(1);
// 每页多少条
const limit = ref(6);
// 总页数
const total = ref(0);
// 多选
const selectedKeys = ref([]);
// 表格的Loading
const isLoading = ref(false);
// 分页器
const pageSizeOptions = ref(['10', '20', '30', '40', '50']);
// const total = ref(50);
const onShowSizeChange = (current, pageSize) => {
    limit.value = pageSize;
    getList();
};

watch(page,()=>{
    console.log(page.value)
    getList();
})

// 请求数据
const getList = async () => {
    isLoading.value = true;
    const params = {
        page: page.value,
        limit: limit.value,
        keyWord: keyWords.value,
    }
    const res = await getBannerListApi(params);
    console.log(res);
    data.value = handlerPicPath(res.data);
    isLoading.value = false;
    total.value = res.total;
}
getList();
// 删除（多选 单个）
const remove = (isOne,record)=>{
    const params = [];
    let message = "";
    if (isOne) {
        // 单选
        const {name,id} = record;
        params.push(id);
        message=name;
    }else{
        // 多选
        const ids = selectedKeys.value.map((item)=>item.id);
        params.push(...ids);
        message = ids.length+"条数据";
    }
    // 1.拦截弹框 是 请求API 成功提示
    Modal.confirm({
    title: '温馨提示',
    icon: createVNode(ExclamationCircleOutlined),
    content: `您确定要删除当前数据?(${message})`,
    async onOk() {
      try {
        return await delBannerListApi(params).then((res)=>{
            if (res.affected>0) {
                Msg.success("恭喜你，操作成功");
            }else{
                Msg.fail("操作失败");
                
            }
            // 刷新当前页面
            getList();
        })
      } catch {
        return console.log('Oops errors!');
      }
    },
    onCancel() {},
  });
}
const router = useRouter();
const onSearch = () => {
    // console.log(value);
    getList();
}
const toAdd = () => {
    console.log('添加');
    router.push({ name: 'BannerAdd' })
}
const toEdit = ({ id }) => {
    console.log('添加');
    router.push({ name: 'BannerEdit', params: { id } })
}
// 多选
const rowSelection = ref({
    checkStrictly: false,
    onChange: (selectedRowKeys, selectedRows) => {
        selectedKeys.value = selectedRows;
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
        selectedKeys.value = selectedRows;
        console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
        selectedKeys.value = selectedRows;
        console.log(selected, selectedRows, changeRows);
    },
});






</script>